package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void insert(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner select(String id) {
        return bannerRepository.findById(id).get();
    }

    @Override
    public Page<Banner> query(QueryObject qo) {
        Query query = new Query();

        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize()
                , Sort.Direction.ASC, "_id");

        return DBHelper.query(mongoTemplate, Banner.class, query, pageable);
    }

    @Override
    public List<Banner> queryTravel() {
        List<Banner> banners = bannerRepository.findByTypeOrderByIdAsc(1);
        banners = banners.subList(0, 5);
        return banners;
    }

    @Override
    public Banner queryStrategy() {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.andOperator(
                Criteria.where("type").is(2),
                Criteria.where("sequence").is(1)
        );
        query.addCriteria(criteria);
        List<Banner> banner = mongoTemplate.find(query, Banner.class, "banner");
        return banner.get(0);
    }
}
